<?php

namespace App\Http\Controllers\Admin;

use App\Console\Commands\SuggestTimeCommand;
use App\Models\AppletsIndexListCategory;
use App\Models\AppTypeModel;
use App\Models\Category;
use App\Models\Config;
use App\Models\Goods;
use App\Models\MarketingActive;
use App\Services\AuthService;
use App\Services\CommonService;
use App\Traits\CurdTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;

class MarketingActiveController extends BaseController
{
    use CurdTrait;
    /**
     * @var MarketingActive
     */
    protected $curdModel;

    /**
     * @MarketActiveController
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->setCurdModel(new MarketingActive());
    }

    /**
     * 列表
     * @param \Illuminate\Http\Request $request
     */
    public function list(Request $request)
    {
        $paramsId = $request->input('id');
        $title= $request->input('title');
        $pageSize = !empty($request['pageSize'])?$request['pageSize']:CommonService::PAGESIZE;
        $type = $request->input('type','1');

        $paginate = $this->curdModel
            ->when($paramsId, function($q) use ($paramsId) {
                $q->where('id', $paramsId);
            })
            ->when($title, function($q) use ($title) {
                $q->where('title', 'like', '%' . $title . '%');
            })
            ->where('type', $type)
            ->select('id', 'create_time', 'id', 'title', 'status', 'begin_time', 'end_time', 'create_by_id', 'mini_id','create_by')
            ->orderBy('id', 'desc')
            ->paginate($pageSize);
        $paginate=obToArray($paginate);
        foreach ($paginate['data'] as $key=>$item){
            $paginate['data'][$key]['mini_name']=AppTypeModel::query()->where('id',$item['mini_id'])->value('app_name');

        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功', $paginate);
    }

    /**
     * 详情
     * @param \Illuminate\Http\Request $request
     */
    public function info(Request $request)
    {
        $id = $request->input('id');
        $model = $this->curdModel->find($id);
        if (empty($model)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'数据不存在');
        }

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$model);
    }

    /**
     * 保存
     * @param \Illuminate\Foundation\Http\FormRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function save(Request $request)
    {
        $id = $request->input('id');
        if ($id) {
            return $this->edit($request);
        }else {
            return $this->add($request);
        }
    }

    /**
     * 添加
     */
    protected function add(Request $request)
    {
        $validator = Validator::make($request->input(), [
            'title' => 'required',

            'content' => 'required',
        ]);

        if ($validator->fails()) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数有误');
        }

        if($request->input('begin_time')&&$request->input('begin_time')>=$request->input('end_time')){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '开始时间不能大于结束时间');
        }
        DB::beginTransaction();
        $saveData=[
            'title' => $request->input('title'),
            'label' => $request->input('label'),
            'color' => $request->input('color'),
            'type' => $request->input('type')??1,
            'mini_id' => $request->input('mini_id')??'',
            'image' => $request->input('image')??'',
            'image_a' => $request->input('image_a')??'',
            'status' => $request->input('status'),
            'is_long' => $request->input('is_long'),
            'begin_time' => $request->input('begin_time'),
            'end_time' => $request->input('end_time'),
            'content' => json_encode($request->input('content')),
            'create_by_id' => AuthService::getInstance()->getAdminId(),
            'create_by' => AuthService::getInstance()->getAdminName(),
        ];
        $row = $this->curdModel->create($saveData);
        if (!$row) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'数据不存在');
        }

        DB::commit();
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'新增成功', ['id' => $row->getKey()]);
    }

    /**
     * 编辑
     */
    protected function edit(Request $request)
    {
        $validator = Validator::make($request->input(), [
            'id' => 'required',
            'title' => 'required',
            'content' => 'required',
        ]);

        if ($validator->fails()) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数有误');
        }

        if($request->input('begin_time')&&$request->input('begin_time')>=$request->input('end_time')){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '开始时间不能大于结束时间');
        }

        $id = $request->input('id');

        $row = $this->curdModel->find($id);
        if (empty($row)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '数据不存在');
        }
        $saveData=[
            'title' => $request->input('title'),
            'begin_time' => $request->input('begin_time'),
            'color' => $request->input('color'),
            'label' => $request->input('label'),
            'status' => $request->input('status'),
            'image' => $request->input('image')??'',
            'image_a' => $request->input('image_a')??'',
            'mini_id' => $request->input('mini_id')??'',
            'type' => $request->input('type')??1,
            'is_long' => $request->input('is_long'),
            'end_time' => $request->input('end_time'),
            'content' => json_encode($request->input('content')),
            'update_by_id' => AuthService::getInstance()->getAdminId(),
            'update_by' => AuthService::getInstance()->getAdminName(),
        ];
        DB::beginTransaction();

        $res = $row->fill($saveData)->save();
        if (!$res) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '数据不存在');
        }

        DB::commit();

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '编辑成功',['id' => $row->getKey()]);
    }

    /**
     * 删除
     */
    public function delete(Request $request)
    {
        $id = $request->input('id');

        $row = $this->curdModel->find($id);
        if (empty($row)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '数据不存在');
        }

        DB::beginTransaction();

        $res = $row->delete();
        if (!$res) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '删除失败');
        }

        DB::commit();

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'删除成功');
    }

    /**
     * 预览
     * @param \Illuminate\Http\Request $request
     */
    public function switchStatus(Request $request)
    {

    }

    public function updateStatus(Request $request)
    {
        $id = $request->input('id');
        $status = $request->input('status');
        if(empty($id)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数有误');
        }


        $row = $this->curdModel->find($id);
        if(empty($row)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'数据不存在');
        }
        $saveData=[
            'status' => $status,
            'update_by_id' => AuthService::getInstance()->getAdminId(),
            'update_by' => AuthService::getInstance()->getAdminName(),
        ];
        DB::beginTransaction();
        $res = $row->fill($saveData)->save();
        if(!$res){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'操作失败');
        }
        DB::commit();
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'操作成功');

    }


    public function pagesRoute(Request $request)
    {
        $pages[]=['id'=>1,'name'=>'首页','page_url'=>'home','sub'=>[['name'=>'首页','page_url'=>'pages/index/index']]];
        $category = Category::where([['enabled',Category::CATEGORY_STATUS_DISPLAY],['is_delete',Category::CATEGORY_NOT_DELETE]])
            ->select('id','name','image','parentid')->orderBy('displayorder','asc')->get();
        $category = $category ? $category->toArray() : [];
        $data = [];
        if(!empty($category)){
            $generateTree = function ($items, $parentKey = 'parentid') {
                $tree = $temp = [];

                foreach ($items as $key=>$item) {

                    $temp[$item['id']] = $item;
                }
                foreach ($items as $item) {
                    if (isset($temp[$item[$parentKey]])) {
                        $temp[$item[$parentKey]]['sub'][] = &$temp[$item['id']];
                    } else {
                        $tree[] = &$temp[$item['id']];
                    }
                    // 下面可以去掉 pid 元素
                    unset($temp[$item['id']][$parentKey]);
                }
                return $tree;
            };
            $data = $generateTree($category);
        }

        foreach ($data as $k=>&$v){
            $v['page_url'] = 'pages/classify/classify?id='.$k;
            if(!empty($v['sub'])){
                foreach ($v['sub'] as $k1=>&$v1){
                    $v1['page_url'] = 'pagesA/pages/productList/productList?cateId='.$v1['id'];
                }
            }
        }
        $pages[]=['id'=>2,'name'=>'分类','page_url'=>'cate','sub'=>$data];

        $data=MarketingActive::query()
            ->where('status',0)
            ->select('id','title as name')
            ->get()->toArray();
        foreach ($data as &$v){
            $v['page_url'] = 'pagesA/pages/promotionPageVariable/promotionPageVariable?id='.$v['id'];
        }
        $pages[]=['id'=>3,'name'=>'活动页','page_url'=>'pagesA/pages/promotionPageVariable/promotionPageVariable','sub'=>$data];

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取',$pages);
    }



    /**
     * 基础设置
     * @param Request $request
     */
    public function editJumps(Request $request){
        $input = $request->input();
        $json=json_encode($input);
        if(!$input['open_jumps']){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数有误');
        }
        $data=Config::where('id',4)->update(['value'=>$json]);
        if($data!==false){
            (new SuggestTimeCommand())->handleExec();
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '修改成功',$data);
        }
        return ReturnMsg(CommonService::HTTP_CODE_FAIL, '修改失败');
    }

    public function getJumps(Request $request){
        $data=Config::where('id',4)->value('value');
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '获取成功',json_decode($data,true));
    }

}
